//
//  JinXCViewController.m
//  KuWoCan
//
//  Created by hwd on 17/3/3.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "JinXCViewController.h"
#import "JinXCCell.h"
#import "DetailJXKCViewController.h"
#import "ESSCommitInventoryVC.h"
#import "NWESSRequest.h"
#import "ESSListModel.h"
#import "CargoChooseVC.h"

@interface JinXCViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *tableV;

@property (nonatomic,assign) NSInteger currentPage;

@property (nonatomic,strong) NSMutableArray *tableArray;
@property (nonatomic, strong) UIView *noCargoView;
@end

@implementation JinXCViewController
#pragma mark - life cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configRefreshControl];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableV];
    [self createBottomBtn];
    if ([[Singleton shareInstance].userType integerValue] != 1) {
        return;
    }
    if ([[[UserModel getUser] isInit] isEqualToString: @"1"])
    {
        //创建列表
        self.title = @"进销库存管理";
        [self.noCargoView removeFromSuperview];
    }
    else
    {
        //创建空白页面
        self.title = @"初始化库存";
        [self createEmptyView];
    }
    if (self.isFirstSubmit) {
//        self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
//        self.navigationItem.hidesBackButton = YES;
    }
}

#pragma mark - Config UI
- (void)createBottomBtn
{
    if (self.isOtherEntrance) {
        return;
    }
    //创建底部按钮
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"更新库存" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(commitBtnAction) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-15);
        make.height.equalTo(@50);
        make.left.equalTo(@15);
        make.right.equalTo(@-15);
    }];
}

- (void)commitBtnAction
{
    NWESSRequest *request = [[NWESSRequest alloc] init];
    [request startRequestCanUpdateInventoryWithUserId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            if ([[result objectForKey:@"isSubmit"] integerValue] == 1)
            {
                ESSCommitInventoryVC *detailVC = [[ESSCommitInventoryVC alloc]init];
                [self.navigationController pushViewController:detailVC animated:YES];
            }
            else
            {
                UIAlertController *alertCtr = [UIAlertController alertControllerWithTitle:@"提示" message:@"每月只能更新一次" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alertCtr addAction:okAction];
                [self presentViewController:alertCtr animated:YES completion:nil];
            }
        }
    }];
}

- (void)configRefreshControl
{
    __weak typeof(self) weakSelf = self;
    self.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        [self.tableV.mj_footer resetNoMoreData];
        [weakSelf loadingDataWithTag:1 showLoading:YES];
    }];
    [self.tableV.mj_header beginRefreshing];

    self.tableV.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadingDataWithTag:0 showLoading:YES];
    }];
}

- (void)createEmptyView
{

    self.noCargoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.noCargoView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.noCargoView];
    
    UIImageView *imgView = [UIImageView new];
    imgView.image = kImg(@"nodata.jpg");
    [self.noCargoView addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(@100);
        make.size.mas_equalTo(CGSizeMake(150, 130));
    }];

    UILabel *lab = [UILabel new];
    lab.textColor = [UIColor grayColor];
    lab.font = KwFont(15);
    lab.text = @"暂无记录,点击完善库存";
    [self.noCargoView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imgView.mas_bottom).offset(20);
        make.centerX.equalTo(imgView.mas_centerX);
        make.height.equalTo(@20);
    }];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"完善库存" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(initInventory) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = KwBlueColor;
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 5;
    [self.noCargoView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab.mas_bottom).offset(40);
        make.centerX.equalTo(imgView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(150 * screenW_6, 40 * screenW_6));
    }];
}

#pragma mark - Load data


#pragma mark - Data request
- (void)loadingDataWithTag:(NSInteger)tag showLoading:(BOOL)isShowLoading
{
//    __weak typeof(self) weakSelf = self;
    NWESSRequest *request = [[NWESSRequest alloc] init];
    [request startRequestGetESSListWithUserId:_personId ? _personId :[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        [self stopRefresh];
        if (succ) {
            if (tag == 1) {
                [self.tableArray removeAllObjects];
            }
            if (result && result != nil)
            {
                NSArray *arr = [ESSListModel arrayOfModelsFromDictionaries:result];
                if (arr.count > 0) {
                    [self.noCargoView removeFromSuperview];
                }
                if ([arr count] == [kPageSize integerValue])
                {
                    _currentPage ++ ;//有下一页  show 加载按钮
                    [self.tableV.mj_footer resetNoMoreData];
                    [self.tableArray addObjectsFromArray:arr];
                }else {
                    [self.tableV.mj_footer endRefreshingWithNoMoreData];
                    [self.tableArray addObjectsFromArray:arr];
                }
                [self.tableV reloadData];
            }
        }
    }];
}

#pragma mark - Registration notice and release


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.tableArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JinXCCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cell%d",(int)indexPath.row]];
    if (cell == nil) {
        cell  = [[JinXCCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"cell%d",(int)indexPath.row]];
    }
    cell.model = self.tableArray[indexPath.section];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.0000001;
    }
    return 5 * screenW_6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00000001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailJXKCViewController *detailVC = [[DetailJXKCViewController alloc]init];
    ESSListModel *model = self.tableArray[indexPath.section];
    detailVC.invoicingId = model.id;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - event response
- (void)initInventory
{
    UserModel *model = [UserModel getUser];
    if ([model.isInit integerValue] == 0)
    {
        //初始化库存,进入酷我产品页面
        CargoChooseVC *vc = [[CargoChooseVC alloc] init];
        vc.type = CargoVCTypeESS;
        vc.isFirstSubmit = YES;
        __weak typeof(self) weakSelf = self;
        vc.reloadBlock = ^{
            [weakSelf loadingDataWithTag:1 showLoading:YES];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - private method
- (void)stopRefresh {
    if ([self.tableV.mj_header isRefreshing]) {
        [self.tableV.mj_header endRefreshing];
    }
    if ([self.tableV.mj_footer isRefreshing]) {
        [self.tableV.mj_footer endRefreshing];
    }
}

#pragma mark - getter and setter
- (UITableView *)tableV {
    if (!_tableV) {
        _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0,0,SCREENW,SCREENH - 64 - 65) style:UITableViewStyleGrouped];
        _tableV.backgroundColor = [UIColor colorWithHexString:@"F6F7F8"];
        _tableV.dataSource = self;
        _tableV.delegate = self;
        _tableV.rowHeight = 75 * screenW_6;
        _tableV.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return _tableV;
}

- (NSMutableArray *)tableArray {
    if (!_tableArray) {
        _tableArray = [NSMutableArray array];
    }
    return _tableArray;
}

@end
